<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>请假申请</title>
   <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
   <style>
        .result-message {
            margin-top: 20px;
            padding: 10px;
            border-radius: 4px;
            display: none;
        }
        .success {
            background-color: #dff0d8;
            color: #3c763d;
        }
        .error {
            background-color: #f2dede;
            color: #a94442;
        }
        .history-section {
            margin-top: 30px;
            display: none;
        }
        .history-section h3 {
            margin-bottom: 15px;
            color: #333;
            border-bottom: 1px solid #ddd;
            padding-bottom: 10px;
        }
        .leave-history-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }
        .leave-history-table th, .leave-history-table td {
            padding: 10px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        .leave-history-table th {
            background-color: #f5f5f5;
            font-weight: bold;
        }
        .leave-status {
            font-weight: bold;
        }
        .status-pending {
            color: #f39c12;
        }
        .status-approved {
            color: #27ae60;
        }
        .status-rejected {
            color: #e74c3c;
        }
        .no-history {
            font-style: italic;
            color: #777;
            text-align: center;
            padding: 20px;
        }
        .admin-comment {
            font-style: italic;
            color: #666;
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .admin-comment:hover {
            white-space: normal;
            overflow: visible;
        }
   </style>
</head>
<body>
    <section class="card">
        <h2>请假申请</h2>
        <form id="leave-form">
            <label for="employee_id">员工ID：</label>
            <input type="text" id="employee_id" name="employee_id" required>

            <label for="leave_type">请假类型：</label>
            <select id="leave_type" name="leave_type" required>
                <option value="sick">病假</option>
                <option value="personal">事假</option>
                <option value="vacation">年假</option>
                <option value="other">其他</option>
            </select>

            <label for="start_date">开始日期：</label>
            <input type="date" id="start_date" name="start_date" required>

            <label for="end_date">结束日期：</label>
            <input type="date" id="end_date" name="end_date" required>

            <label for="reason">请假原因：</label>
            <textarea id="reason" name="reason"></textarea>

            <button type="submit">提交申请</button>
        </form>
        
        <div id="result-message" class="result-message"></div>
        
        <div class="button-container">
            <a href="/" class="button secondary">返回首页</a>
            <button id="check-history-btn" class="button primary">查看请假历史</button>
        </div>
        
        <!-- 请假历史部分 -->
        <div id="leave-history" class="history-section">
            <h3>请假历史记录</h3>
            <div id="leave-history-content">
                <p class="no-history">请先输入员工ID并点击"查看请假历史"</p>
            </div>
        </div>
    </section>
    <script>
        document.getElementById('leave-form').addEventListener('submit', async (event) => {
            event.preventDefault();
            
            // Get form data
            const formData = {
                employee_id: document.getElementById('employee_id').value,
                leave_type: document.getElementById('leave_type').value,
                start_date: document.getElementById('start_date').value,
                end_date: document.getElementById('end_date').value,
                reason: document.getElementById('reason').value
            };
            
            try {
                // Send data to server
                const response = await fetch('/leave_request', {
                    method: 'POST',
                    body: JSON.stringify(formData),
                    headers: {'Content-Type': 'application/json'}
                });

                const result = await response.json();
                
                // Display result
                const resultElement = document.getElementById('result-message');
                resultElement.textContent = result.message;
                resultElement.className = result.success ? 'result-message success' : 'result-message error';
                resultElement.style.display = 'block';
                
                // Clear form if successful
                if (result.success) {
                    document.getElementById('leave-form').reset();
                    // 如果成功提交，自动加载历史记录
                    loadLeaveHistory(formData.employee_id);
                }
            } catch (error) {
                console.error('Error submitting form:', error);
                
                // Display error message
                const resultElement = document.getElementById('result-message');
                resultElement.textContent = '提交失败，请稍后重试';
                resultElement.className = 'result-message error';
                resultElement.style.display = 'block';
            }
        });
        
        // 查看请假历史功能
        document.getElementById('check-history-btn').addEventListener('click', () => {
            const employeeId = document.getElementById('employee_id').value;
            if (!employeeId) {
                alert('请先输入员工ID');
                return;
            }
            loadLeaveHistory(employeeId);
        });
        
        // 加载请假历史记录
        async function loadLeaveHistory(employeeId) {
            try {
                const response = await fetch(`/api/employee/leave-history/${employeeId}`);
                const data = await response.json();
                
                const historySection = document.getElementById('leave-history');
                const historyContent = document.getElementById('leave-history-content');
                historySection.style.display = 'block';
                
                if (data.error) {
                    historyContent.innerHTML = `<p class="error">${data.error}</p>`;
                    return;
                }
                
                if (data.length === 0) {
                    historyContent.innerHTML = '<p class="no-history">没有找到请假记录</p>';
                    return;
                }
                
                // 构建历史记录表格
                let tableHTML = `
                    <table class="leave-history-table">
                        <thead>
                            <tr>
                                <th>申请日期</th>
                                <th>请假类型</th>
                                <th>开始日期</th>
                                <th>结束日期</th>
                                <th>原因</th>
                                <th>状态</th>
                                <th>管理员回复</th>
                            </tr>
                        </thead>
                        <tbody>
                `;
                
                const leaveTypeMap = {
                    'sick': '病假',
                    'personal': '事假',
                    'vacation': '年假',
                    'other': '其他'
                };
                
                const statusMap = {
                    'pending': '待审批',
                    'approved': '已批准',
                    'rejected': '已拒绝'
                };
                
                const statusClassMap = {
                    'pending': 'status-pending',
                    'approved': 'status-approved',
                    'rejected': 'status-rejected'
                };
                
                data.forEach(record => {
                    const createdAt = new Date(record.created_at).toLocaleDateString();
                    const startDate = new Date(record.start_date).toLocaleDateString();
                    const endDate = new Date(record.end_date).toLocaleDateString();
                    const leaveType = leaveTypeMap[record.leave_type] || record.leave_type;
                    const status = statusMap[record.status] || record.status;
                    const statusClass = statusClassMap[record.status] || '';
                    
                    tableHTML += `
                        <tr>
                            <td>${createdAt}</td>
                            <td>${leaveType}</td>
                            <td>${startDate}</td>
                            <td>${endDate}</td>
                            <td>${record.reason || '-'}</td>
                            <td class="leave-status ${statusClass}">${status}</td>
                            <td class="admin-comment">${record.admin_comment || '-'}</td>
                        </tr>
                    `;
                });
                
                tableHTML += `
                        </tbody>
                    </table>
                `;
                
                historyContent.innerHTML = tableHTML;
                
            } catch (error) {
                console.error('Error loading leave history:', error);
                document.getElementById('leave-history-content').innerHTML = 
                    '<p class="error">加载请假历史失败，请稍后重试</p>';
            }
        }
    </script>
</body>
</html>
